package Demo1;

public class Solution {
    public static int lengthOfLongestSubstring(String s) {
        int cursor = 0;
        int headOfSubstring = 0;
        int lenghOfSubstring = 0;
        int longestLengthOfSubstring = 0;
        while (cursor < s.length()) {
            //从{headOfSubstring}开始向后查找
            char ch = s.charAt(cursor);
            int indexOfDuplicateChar = s.indexOf(ch, headOfSubstring);
            if (indexOfDuplicateChar < cursor) {
                longestLengthOfSubstring = lenghOfSubstring > longestLengthOfSubstring? lenghOfSubstring:longestLengthOfSubstring;

                //假设之后没有重复的字符出现，则之后的最长子字符串就是{indexOfDuplicateChar}到结尾的长度
                //如果这个长度还没有之前的结果长，那可以直接跳出循环，不需要再比较了
                //这一段是通过预估减少循环次数，即使去掉也能得到正确结果
                int longestLengthOfRestSubstring = s.length() - indexOfDuplicateChar - 1;
                if (longestLengthOfSubstring >= longestLengthOfRestSubstring) {
                    return longestLengthOfSubstring;
                }

                lenghOfSubstring = cursor - indexOfDuplicateChar;
                headOfSubstring = indexOfDuplicateChar + 1;
            } else {
                lenghOfSubstring++;
            }
            cursor++;
        }
        return lenghOfSubstring > longestLengthOfSubstring ? lenghOfSubstring : longestLengthOfSubstring;
    }
}